<template>
  <div>
    <!-- 图片上传组件 -->
    <el-upload
      action="#"
      list-type="picture-card"
      :http-request="upImg"
      :file-list="imgurl?[{url:imgurl}]:[]"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :class="{dispaly:imgurl?true:false}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-show="perisho" :percentage="percen" status="success" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
  SecretId: 'AKIDMcfYJrD2gBVbTAddR3SgjbFfuwnRuDMI',
  SecretKey: 'kIhvwlOo494pOk05xd5LQIzWpwsb6Shk'
})
export default {
  data() {
    return {
      imgurl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      percen: 0,
      perisho: false
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.$emit('remove')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    upImg(file) {
      this.perisho = true
      cos.uploadFile({
        Bucket: 'hr-82-1314826467', /* 填写自己的bucket，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(), /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file.file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          this.percen = progressData.percent * 100
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
          this.perisho = false
        } else {
          console.log('上传成功', data)
          this.$emit('upImg', 'https://' + data.Location)
          this.perisho = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dispaly{
    ::v-deep .el-upload--picture-card{
        display: none;
    }
}
.l-progress{
    width: 180px;
}
</style>
